from django.db import models

from user.models import User


class Coach(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="用户")
    bio = models.TextField(verbose_name="教练简介", blank=True)
    specialization = models.CharField(max_length=100, verbose_name="专长领域", blank=True)
    certification = models.CharField(max_length=200, verbose_name="认证信息", blank=True)

    class Meta:
        verbose_name = "教练"
        verbose_name_plural = "教练"

    def __str__(self):
        return self.user.get_full_name() or self.user.username


class Course(models.Model):
    STATUS_CHOICES = (
        ('draft', '草稿'),
        ('published', '已发布'),
        ('archived', '已归档'),
    )

    DIFFICULTY_CHOICES = (
        ('easy', '简单'),
        ('medium', '中等'),
        ('hard', '困难'),
    )

    # 课程基本与详情信息字段
    title = models.CharField(max_length=100, verbose_name="课程名称", null=False)
    coach = models.ForeignKey(Coach, on_delete=models.SET_NULL, null=True, verbose_name="教练")
    is_free = models.BooleanField(default=False, verbose_name="是否免费", null=False)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="课程价格")
    description = models.TextField(verbose_name="课程描述", blank=True, null=True)
    duration = models.IntegerField(verbose_name="课程时长(分钟)", blank=True, null=True)
    difficulty = models.CharField(
        max_length=10,
        choices=DIFFICULTY_CHOICES,
        verbose_name="难度级别",
        blank=True, null=True
    )
    type = models.CharField(max_length=50, verbose_name="课程类型（瑜伽/力量等）", blank=True, null=True)
    cover_url = models.URLField(max_length=200, verbose_name="封面图URL", blank=True, null=True)
    video_url = models.URLField(max_length=200, verbose_name="教学视频URL", blank=True, null=True)

    # 状态与版本控制字段
    status = models.CharField(
        max_length=10,
        choices=STATUS_CHOICES,
        default='draft',
        verbose_name="课程状态"
    )
    version = models.IntegerField(default=1, verbose_name="版本号")

    # 学习进度追踪相关字段
    learn_count = models.IntegerField(default=0, verbose_name="学习人数")
    avg_progress = models.DecimalField(max_digits=5, decimal_places=2, default=0, verbose_name="平均学习进度(%)")

    # 时间戳字段
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "课程"
        verbose_name_plural = "课程"
        indexes = [
            models.Index(fields=['status']),
            models.Index(fields=['type']),
            models.Index(fields=['coach']),
        ]

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        # 如果是更新操作，增加版本号
        if self.pk:
            self.version += 1
        super().save(*args, **kwargs)


class CourseSubscription(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name="课程")
    subscribed_at = models.DateTimeField(auto_now_add=True, verbose_name="订阅时间")
    is_active = models.BooleanField(default=True, verbose_name="是否激活")

    class Meta:
        verbose_name = "课程订阅"
        verbose_name_plural = "课程订阅"
        unique_together = (('user', 'course'),)

    def __str__(self):
        return f"{self.user.username} - {self.course.title}"

